// Copyright 2023 Guo Tingjin(ericple)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { zip } from "compressing";
import checkPath from "../utils/checkPath";
import HAPV_CONSTANTS from "../hapvConstants";
import readMap from "../utils/readMap";
import path from 'path';
import fs from 'fs'
import HapInfo from "../type/hapInfo";
import HapInstance from "../type/hapInstance";

class hapvCore {
    private static _arg: Map<string, string>;
    private static async ExtractHap() {
        let fPath = checkPath(readMap(this._arg, HAPV_CONSTANTS.NAMED_ARGUMENTS.IN_FILE));
        if (!fPath) {
            console.error(`Error: unreachable input file: ${readMap(this._arg, HAPV_CONSTANTS.NAMED_ARGUMENTS.IN_FILE)}`);
            process.exit(-1);
        }
        let unzipPath = path.join(readMap(this._arg, HAPV_CONSTANTS.NAMED_ARGUMENTS.WORK_DIR), '.hapvcache');
        try {
            await zip.uncompress(fPath, unzipPath);
            return unzipPath;
        } catch (e) {
            console.error(`Error: ${e}`);
            process.exit(-1);
        }
    }
    public static async Process(argMap: Map<string, string>) {
        this._arg = argMap;
        let unzipPath = await this.ExtractHap();
        const packInfoPath = path.join(unzipPath, 'pack.info');
        const moduleInfoPath = path.join(unzipPath, 'module.json');
        const resourcesIndexPath = path.join(unzipPath, 'resources.index');
        console.info('Reading resources buffer...');
        const resourcesBuffer = fs.readFileSync(resourcesIndexPath);
        console.info(`Reading modules information...`);
        const moduleInfo: HapInfo = JSON.parse(fs.readFileSync(moduleInfoPath, 'utf-8'));
        const hapInstance = new HapInstance(moduleInfo, unzipPath, resourcesBuffer, argMap);
        hapInstance.processArg(argMap);
    }
}

export default hapvCore;